﻿#include <QTimer>
#include <QDebug>

#include "TcpSendReplyClient.h"
#include "quihelperdata.h"

TcpSendReplyClient::TcpSendReplyClient(QObject *parent):BaseSendReply(parent)
{
    _socket=new QTcpSocket();
    _timer=new QTimer(this);
    connect(_socket,  SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(OnError1(QAbstractSocket::SocketError)));
}

TcpSendReplyClient::~TcpSendReplyClient()
{
    _timer->deleteLater();
    Dispose();
}

void TcpSendReplyClient::Reconnect()
{
    _socket->abort(); // 中止当前连接
    bool ret=Connect(); // 重新连接到服务器
    qDebug() << "Reconnecting to server..."<<ret;
}

bool TcpSendReplyClient::IsConnected()
{
    return _socket->state()==QAbstractSocket::SocketState::ConnectedState;
}

bool TcpSendReplyClient::Connect()
{
    QString hostaddr = _communicationParam.split(":").at(0);
    int strportID = _communicationParam.split(":").at(1).toInt();
    _socket->connectToHost(hostaddr,strportID);
    _socket->setSocketOption(QAbstractSocket::KeepAliveOption,1);
    return _socket->waitForConnected(1000);
}

void TcpSendReplyClient::Dispose()
{
    if(_socket)
    {
        _socket->abort();
        delete _socket;
    }
}

void TcpSendReplyClient::SetOtherConfig(QJsonObject obj)
{
    BaseCommunication::SetOtherConfig(obj);
    _timeout=_other["TimeoutMs"].toInt();
    if(_timeout<=0)
    {
        throw QString("TcpSendReplyClient timeout 有误:%1").arg(_timeout);
    }

    if(obj["EnableHeartBeat"].toBool())
    {
        qDebug()<<__FUNCTION__<<__LINE__<<obj;
        connect(_timer,&QTimer::timeout,this,&TcpSendReplyClient::HeadrBeat);
        _timer->setInterval(obj["InternalSecond"].toInt()*1000);
        _timer->start();
    }
}

bool TcpSendReplyClient::DisConnect()
{
    _socket->abort();
    return true;
}

bool TcpSendReplyClient::SendReply(QByteArray sendBuff, QByteArray &receiveBuff)
{
    for(int i=0;i<3;i++)
    {
        bool sendResult=SendReplyImpl(sendBuff,receiveBuff,_timeout);

        if(sendResult)
        {
            return true;
        }
        else
        {
            Reconnect();
            qDebug()<<__FUNCTION__<<__LINE__<<"Reconnected:";
        }
    }
    throw QString("数据连续三次发送失败:%1").arg(_socket->errorString());
}

bool TcpSendReplyClient::SendReplyImpl(QByteArray sendBuff, QByteArray &receiveBuff, int timeoutMs)
{
    QMutexLocker locker(&mutex);
    _socket->readAll();
    int ret=_socket->write(sendBuff);
    _socket->waitForBytesWritten(timeoutMs);
    if(ret!=sendBuff.size())
    {
        return false;
    }
    if(!_socket->waitForReadyRead(timeoutMs))
    {
        return false;
    }

    receiveBuff=_socket->readAll();
    qInfo()<<_name<<__FUNCTION__<<__LINE__<<"Receive:"<<QUIHelperData::byteArrayToHexStr(receiveBuff);
    emit DataReceive(receiveBuff);
    return true;
}

bool TcpSendReplyClient::HeadrBeat()
{
    QByteArray sendCommand=QByteArray::fromHex(_other["SendCommand"].toString().trimmed().toLatin1());
    QByteArray recv;

    bool ret=SendReplyImpl(sendCommand,recv,_timeout);
    if(!ret)
    {
        qDebug()<<GetCommunicationParam()<<"心跳测试失败!";
    }
    return ret;
}

void TcpSendReplyClient::OnError1(QAbstractSocket::SocketError err)
{
    qDebug()<<__FUNCTION__<<_name<<"scoket error"<<err<<_socket->errorString();
}


bool TcpSendReplyClient::SendNoReply(QByteArray sendBuff)
{
    int ret=_socket->write(sendBuff);
    _socket->waitForBytesWritten(100);
    if(ret!=sendBuff.size())
    {
        return false;
    }
    {
        return true;
    }
}
